package com.cug.nageoffer.common.service.impl;

import com.alibaba.fastjson.JSON;
import com.cug.nageoffer.common.mapper.JobMapper;
import com.cug.nageoffer.common.service.JobService;
import com.cug.nageoffer.model.entity.Job;
import com.cug.nageoffer.model.vo.JobVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class JobServiceImpl implements JobService {

    @Autowired
    private JobMapper jobMapper;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 根据分类名称分页查询岗位
     */
    @Override
//    @Cacheable(value = "job" , key = "#categoryName")
    public PageInfo<JobVo> getJobsByCategoryName(String categoryName, Integer pageNum, Integer pageSize) {

        String cacheKey = "job:page:"+ categoryName + ":" +pageNum + ":" + pageSize;
        // 查询redis查看是否有分页数据
        String cachedData = redisTemplate.opsForValue().get(cacheKey);
        PageInfo<JobVo> pageInfoCache = (PageInfo<JobVo>)JSON.parseObject(cachedData,PageInfo.class);
        if(pageInfoCache != null && pageInfoCache.getList().isEmpty()){
            // 如果缓存数据存在，则直接返回
            pageInfoCache.setPageNum(pageNum);
            pageInfoCache.setPageSize(pageSize);
            return pageInfoCache;
        }else {
            PageHelper.startPage(pageNum,pageSize);
            List<JobVo> jobs = jobMapper.selectByCategoryName(categoryName);
            PageInfo<JobVo> pageInfo = new PageInfo<>(jobs);
            Random random = new Random();
            int timeOut = random.nextInt(1,5);
            // 将查询结果存储到Redis缓存中
            redisTemplate.opsForValue().set(cacheKey, JSON.toJSONString(pageInfo), timeOut ,TimeUnit.HOURS);
            return pageInfo;
        }


    }

    /**
     * 根据公司id查询岗位
     * @param id
     * @return
     */
    @Override
    @Cacheable(value = "job:enterprise" , key = "#id")
    public List<JobVo> getByEnterpriseId(Long id) {
        return jobMapper.selectByEnterpriseId(id);
    }

    /**
     * 根据岗位id查询岗位
     * @return
     */

    @Override
    @Cacheable(value = "job",key = "#id")
    public Job getById(Long id) {
        return jobMapper.selectById(id);
    }
}
